package cn.zc.system.service.impl;

import cn.zc.common.core.domain.R;
import cn.zc.common.core.enums.ResultCode;
import cn.zc.common.core.enums.UserIdentity;
import cn.zc.security.service.TokenService;
import cn.zc.system.domain.dto.LoginDTO;
import cn.zc.system.domain.dto.SysUserSaveDTO;
import cn.zc.system.domain.po.SysUser;
import cn.zc.system.mapper.SysUserMapper;
import cn.zc.system.service.ISysUserService;
import cn.zc.system.util.BCryptUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张策
 * @since 2024-11-20
 */
@Service
@RefreshScope
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TokenService tokenService;
    @Value("${jwt.secret}")
    private String secret;
    @Override
    public R<String> login(LoginDTO loginDTO) {
        LambdaQueryWrapper<SysUser> sysUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        SysUser sysUser = sysUserMapper.selectOne(sysUserLambdaQueryWrapper.select(
                SysUser::getPassword,SysUser::getUserAccount).eq(SysUser::getUserAccount, loginDTO.getUserAccount()));
        if(sysUser==null){
            return R.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }else if (BCryptUtils.matchesPassword(loginDTO.getPassword(), sysUser.getPassword())){
            String token = tokenService.createToken(sysUser.getUserAccount(), secret, UserIdentity.ADMIN.getValue());
            return R.ok(token);
        }
        return R.fail(ResultCode.FAILED_LOGIN);
    }

    @Override
    public R add(SysUserSaveDTO saveDTO) {
        int insert = sysUserMapper.insert(new SysUser(saveDTO.getUserAccount(), saveDTO.getPassword()));
        R<Void> r = new R<>();
        if (insert > 0){
            r.setCode(ResultCode.SUCCESS.getCode());
            r.setMsg(ResultCode.SUCCESS.getMessage());
        }else {
            r.setCode(ResultCode.FAILED.getCode());
            r.setMsg(ResultCode.FAILED.getMessage());
        }
        return r;
    }
}
